import cv2
import numpy as np

# 1. 读取图像
img = cv2.imread("flower.jpg")
if img is None:
    print("图片读取失败！")
    exit()
result = img.copy()
h, w = img.shape[:2]

# 2. 提取花的颜色区域（黄色系）
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_yellow = np.array([20, 100, 100])
upper_yellow = np.array([30, 255, 255])
flower_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)

# 3. 提取手的颜色区域（肤色系）
lower_skin = np.array([0, 20, 70])
upper_skin = np.array([20, 255, 255])
skin_mask = cv2.inRange(hsv, lower_skin, upper_skin)

# 4. 提取花茎的颜色区域（绿色系）
lower_green = np.array([35, 40, 40])   # 绿色HSV下限
upper_green = np.array([77, 255, 255]) # 绿色HSV上限
stem_mask = cv2.inRange(hsv, lower_green, upper_green)

# 5. 合并花、手、花茎的掩码
foreground_mask = cv2.bitwise_or(flower_mask, skin_mask)
foreground_mask = cv2.bitwise_or(foreground_mask, stem_mask)

# 6. 形态学优化（填充空隙、去除噪点）
kernel = np.ones((5,5), np.uint8)
foreground_mask = cv2.morphologyEx(foreground_mask, cv2.MORPH_CLOSE, kernel, iterations=2)
foreground_mask = cv2.morphologyEx(foreground_mask, cv2.MORPH_OPEN, kernel, iterations=1)

# 7. 对背景区域模糊
bg_blur = cv2.GaussianBlur(img, (25, 25), 0)

# 8. 融合前景（清晰）和背景（模糊）
foreground = cv2.bitwise_and(img, img, mask=foreground_mask)
background = cv2.bitwise_and(bg_blur, bg_blur, mask=cv2.bitwise_not(foreground_mask))
result = cv2.add(foreground, background)

# 9. 显示并保存
cv2.namedWindow('result', cv2.WINDOW_NORMAL)
cv2.resizeWindow('result', 800, 600)
cv2.imshow("result", result)
cv2.imwrite("holding_flower.jpg", result)
cv2.waitKey(0)
cv2.destroyAllWindows()